package com.nextel.project.dao;

import com.nextel.project.canje.bean.CabCanjeBean;
import com.nextel.project.cobranza.bean.PagoBean;
import com.nextel.project.devolucion.bean.DevolucionBean;
import com.nextel.project.pedido.bean.PedidoBean;
import com.nextel.project.pedido.bean.PedidoReporteBean;
import com.nextel.project.stock.bean.StockDetalleBean;
import com.nextel.project.usuario.bean.PendientesBean;
import com.nextel.project.usuario.bean.UsuarioBean;
import pe.com.nextel.rms.DataInputStreamX;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.kxml2.io.KXmlParser;
import org.kxml2.io.KXmlSerializer;
import org.xmlpull.v1.XmlPullParser;
import pe.com.nextel.util.ArrayList;
import pe.com.nextel.util.Iterator;
import pe.com.nextel.util.List;

/**
 *
 * @author eespinoza
 */
public class XMLDAO {

    private static final XMLDAO xml = new XMLDAO();

    public static XMLDAO getInstance() {
        return xml;
    }

    private XMLDAO() {
    }

    /*
    /**********************************/
    /* Usuarios
    /**********************************/
    //Genero el documento XML que envio al servidor para validar el ingreso
    //Parseo el xml con los datos del Usuario
    public UsuarioBean parseXMLUsuario(KXmlParser parser) throws Exception {
        UsuarioBean usuario = null;

        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("u") && (parser.getAttributeCount() > 0)) {//si se lee un usuario

                        usuario = new UsuarioBean();
                        usuario.readXMLObject(parser);
                    }

                    if (parser.getName().equals("e") && (parser.getAttributeCount() > 0)) {
                        //si se lee un usuario
                        throw new Exception(parser.getAttributeValue(null, "m"));
                    }
                    break;
            }
            eventType = parser.next();
        }
        return usuario;
    }

    /**********************************/
    /*  Pedido                       */
    /*********************************/
    public void parseMensaje(KXmlParser parser) throws Exception {

        System.out.println("XMLDAO.parseMensaje");
        
        while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {

            parser.next();

            // el XMLElement inicia en "r" y no "e"
            // <?xml version='1.0' encoding='ISO-8859-1'?> <r m='error' db='' du='' />
            
            //if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equals("e")) {
            if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equals("r")) {
                
                throw new Exception(parser.getAttributeValue(null, "m"));
            }
        }
    }

    public void parseMensajeXML(InputStream in) throws Exception {
        
        KXmlParser parser = new KXmlParser();
        InputStreamReader inputReader = new InputStreamReader(in);
        
        parser.setInput(inputReader);

        while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
            parser.next();
            if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equals("r")) {
                String msg = parser.getAttributeValue(null, "m");
                
                if (!msg.trim().equals("")) {
                    throw new Exception(msg.trim());
                }
            }
        }
    }

    public void parseMensaje(InputStream in) throws Exception {
        DataInputStreamX dataInputStream = null;

        try {
            dataInputStream = new DataInputStreamX(in);
            String mensaje = dataInputStream.readString();
            //System.out.println("mensaje " + mensaje);
            if (!"".equals(mensaje)) {
                throw new Exception(mensaje);
            }

        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
                if (dataInputStream != null) {
                    dataInputStream.close();
                    dataInputStream = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String writeXMLTodo(List listaPedido, List listaPago, List listaCanje, List listaDevolucion) throws Exception {
        StringBuffer str = new StringBuffer();
        str.append("<pd>");
        str.append(writeXMLPedido(listaPedido));
        str.append(writeXMLPago(listaPago));
        str.append(writeXMLCanje(listaCanje));
        str.append(writeXMLDevolucion(listaDevolucion));
        str.append("</pd>");
        return str.toString();
    }

    public String writeXMLPedido(List lista) throws Exception {
        StringBuffer str = new StringBuffer();
        str.append("<lp>");
        for (Iterator it = lista.iterator(); it.hasNext();) {
            PedidoBean bean = (PedidoBean) it.next();
            str.append(new String(bean.writeXML()));
        }
        str.append("</lp>");
        return str.toString();
    }

    public String writeXMLPedido(PedidoBean bean) throws Exception {
        StringBuffer str = new StringBuffer();
        str.append("<lp>");
        str.append(new String(bean.writeXML()));
        str.append("</lp>");
        return str.toString();
    }

    public void parseXMLServicio(KXmlParser parser) throws Exception {
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG && parser.getName().equals("e")) {//si se lee un usuario

                throw new Exception(parser.getAttributeValue(null, "m"));
            }
            eventType = parser.next();
        }

    }

    public PedidoReporteBean parseXMLCantidadPedido(KXmlParser parser) throws Exception {
        PedidoReporteBean bean = null;

        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("p") && (parser.getAttributeCount() > 0)) {//si se lee un usuario

                        bean = new PedidoReporteBean();
                        bean.readXMLObject(parser);
                    }

                    if (parser.getName().equals("e") && (parser.getAttributeCount() > 0)) {
                        //si se lee un usuario
                        throw new Exception(parser.getAttributeValue(null, "m"));
                    }
                    break;
            }
            eventType = parser.next();
        }
        return bean;
    }

    public StockDetalleBean parseXMLStock(KXmlParser parser) throws Exception {
        StockDetalleBean bean = null;

        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("p") && (parser.getAttributeCount() > 0)) {//si se lee un usuario

                        bean = new StockDetalleBean();
                        bean.readXMLObject(parser);
                    }

                    if (parser.getName().equals("e") && (parser.getAttributeCount() > 0)) {
                        //si se lee un usuario
                        throw new Exception(parser.getAttributeValue(null, "m"));
                    }
                    break;
            }
            eventType = parser.next();
        }
        return bean;
    }

    public List parseXMLStockNombre(KXmlParser parser) throws Exception {
        StockDetalleBean bean = null;

        int eventType = parser.getEventType();
        List listaBean = new ArrayList();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("p") && (parser.getAttributeCount() > 0)) {//si se lee un usuario

                        bean = new StockDetalleBean();
                        bean.readXMLObject(parser);
                        listaBean.add(bean);
                    }

                    if (parser.getName().equals("e") && (parser.getAttributeCount() > 0)) {
                        //si se lee un usuario
                        throw new Exception(parser.getAttributeValue(null, "m"));
                    }
                    break;
            }
            eventType = parser.next();
        }
        return listaBean;
    }

    /**
     * Arma el xml de ingreso
     * @param lregistros
     * @return Arreglo de bites del xml
     * @throws java.lang.Exception
     */
//    public String writeXMLIngreso(List lregistros) throws Exception
//    {
//        System.out.println("XMLDAO - writeXMLIngreso");
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
//        KXmlSerializer writer = new KXmlSerializer();
//        OutputStreamWriter outWriter = null;
//        PedidoBean pbean=null;
//
//        try
//        {
//            System.out.println("Ingresa Try");
//            outWriter = new OutputStreamWriter(out);
//            writer.setOutput(outWriter);
//
//            writer.startTag(null,"tbl");
//            int cant = lregistros.size();
//            System.out.println("CANTIDAD: "+cant);
//
//            for(int i=0;i<cant;i++)
//            {
//                pbean = (PedidoBean)lregistros.get(i);
//                System.out.println("pbean ==" + pbean);
//                pbean.writeXMLObject(writer);
//
//            }
//
//            writer.endTag(null, "tbl");
//            writer.endDocument();
//            return out.toString();
//        }
//        catch(Exception e)
//        {
//            e.printStackTrace();
//            throw e;
//        }
//        finally
//        {
//            if (out != null) {
//                out.close();
//                out = null;
//            }
//            if (outWriter != null) {
//                outWriter.close();
//                outWriter = null;
//            }
//            if (writer != null) {
//                writer = null;
//            }
//        }
//    }
    public String writeXMLDevolucion(List ldevolucion) throws Exception {
        System.out.println("XMLDAO - writeXMLDevolucion");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        KXmlSerializer writer = new KXmlSerializer();
        OutputStreamWriter outWriter = null;
        DevolucionBean dvbean = null;
        try {
            outWriter = new OutputStreamWriter(out);
            writer.setOutput(outWriter);
            //writeXMLObject(writer);
            writer.startTag(null, "lde");
            int cant = ldevolucion.size();
           // System.out.println("CANTIDAD: " + cant);
            //writer.attribute(null, "n", String.valueOf(cant));
            for (int i = 0; i < cant; i++) {
                dvbean = (DevolucionBean) ldevolucion.get(i);
                dvbean.writeXMLObject(writer);
            }
            writer.endTag(null, "lde");
            writer.endDocument();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
            if (outWriter != null) {
                outWriter.close();
                outWriter = null;
            }
            if (writer != null) {
                writer = null;
            }
        }
    }

    public String writeXMLCanje(List lcanje) throws Exception {
        System.out.println("XMLDAO - writeXMLCanje");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        KXmlSerializer writer = new KXmlSerializer();
        OutputStreamWriter outWriter = null;
        CabCanjeBean cbean = null;
        try {
            outWriter = new OutputStreamWriter(out);
            writer.setOutput(outWriter);
            //writeXMLObject(writer);
            writer.startTag(null, "lca");
            int cant = lcanje.size();
            //System.out.println("CANTIDAD: " + cant);
            //writer.attribute(null, "n", String.valueOf(cant));
            for (int i = 0; i < cant; i++) {
                cbean = (CabCanjeBean) lcanje.get(i);
                cbean.writeXMLObject(writer);
            }
            writer.endTag(null, "lca");
            writer.endDocument();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
            if (outWriter != null) {
                outWriter.close();
                outWriter = null;
            }
            if (writer != null) {
                writer = null;
            }
        }
    }

    public String writeXMLPago(List lpago) throws Exception {
        System.out.println("XMLDAO - writeXMLCanje");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        KXmlSerializer writer = new KXmlSerializer();
        OutputStreamWriter outWriter = null;
        PagoBean pbean = null;
        try {
            outWriter = new OutputStreamWriter(out);
            writer.setOutput(outWriter);
            //writeXMLObject(writer);
            writer.startTag(null, "lpa");
            int cant = lpago.size();
            //System.out.println("CANTIDAD: " + cant);
            //writer.attribute(null, "n", String.valueOf(cant));
            for (int i = 0; i < cant; i++) {
                pbean = (PagoBean) lpago.get(i);
                pbean.writeXMLObject(writer);
            }
            writer.endTag(null, "lpa");
            writer.endDocument();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
            if (outWriter != null) {
                outWriter.close();
                outWriter = null;
            }
            if (writer != null) {
                writer = null;
            }
        }
    }
}

